<?php

declare(strict_types=1);

namespace app\common\model;

use app\common\traits\HasLanguage;
use think\Model;
use think\model\concern\SoftDelete;

class Dict extends Model
{
    use HasLanguage,SoftDelete;

    protected $pk = 'dict_id';

    // 自动时间戳类型
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 定义需要多语言处理的字段
    protected $langFields = ['name', 'remark'];

    // 自动完成
    protected $insert = ['sort' => 0, 'status' => 1];

    // 字段类型转换
    protected $type = [
        'sort' => 'integer'
    ];

    /**
     * 获取字典项目数量
     * @return int
     */
    public function getItemCountAttr()
    {
        return $this->hasMany('DictItem', 'dict_id', 'dict_id')->count();
    }

    /**
     * 关联语言表
     * @return \think\model\relation\HasMany
     */
    public function langs()
    {
        return $this->hasMany(DictLang::class, 'dict_id', 'dict_id')
            ->field(['dict_lang_id', 'dict_id', 'language_id', 'name', 'remark'])
            ->order('language_id', 'asc');
    }

    /**
     * 搜索器：按名称搜索
     * @param $query
     * @param $value
     */
    public function searchNameAttr($query, $value)
    {
        if ($value) {
            // 获取当前语言ID
            $langId = self::getCurrentLanguageId();
            
            // 通过子查询获取匹配的dict_id
            $subQuery = DictLang::where('language_id', $langId)
                ->whereLike('name', "%{$value}%")
                ->field('dict_id')
                ->select()
                ->toArray();

            $subQuery = array_column($subQuery, 'dict_id');

            // 主查询匹配dict_id
            $query->whereIn('dict_id', $subQuery);
        }
    }

    /**
     * 搜索器：按状态搜索
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchStatusAttr($query, $value, $data)
    {
        if (isset($value) && $value !== '') {
            $query->where('status', (int)$value);
        }
    }

    /**
     * 获取所有语言版本数据
     * @return array
     */
    public function getAllLangData()
    {
        $data = [];
        $langs = $this->langs()->select();

        foreach ($langs as $lang) {
            $data[$lang->language_id] = [
                'name' => $lang->name,
                'remark' => $lang->remark
            ];
        }

        return $data;
    }

    /**
     * 保存多语言数据
     * @param array $langData 语言数据 [language_id => ['name' => '', 'remark' => '']]
     * @return bool
     */
    public function saveLangData(array $langData)
    {
        foreach ($langData as $langId => $data) {
            // 查找已存在的语言数据
            $lang = $this->langs()->where('language_id', $langId)->find();

            if ($lang) {
                // 更新
                $lang->save([
                    'name' => $data['name'],
                    'remark' => $data['remark'] ?? ''
                ]);
            } else {
                // 新增
                $this->langs()->save([
                    'language_id' => $langId,
                    'name' => $data['name'],
                    'remark' => $data['remark'] ?? ''
                ]);
            }
        }

        return true;
    }

    /**
     * 删除多语言数据
     * @return bool
     */
    public function deleteLangData()
    {
        return $this->langs()->delete() !== false;
    }
}
